package com.sctvcloud.qingchuan.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseAccountActivity;
import com.sctvcloud.qingchuan.beans.AccountBean;
import com.sctvcloud.qingchuan.beans.AccountTagBean;
import com.sctvcloud.qingchuan.beans.AccountVo;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.adapter.AccountAdapter;
import com.sctvcloud.qingchuan.ui.adapter.AccountTypeAdapter;
import com.sctvcloud.qingchuan.ui.util.IListShowData;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.ui.utils.TitleUtils;
import com.sctvcloud.qingchuan.utils.ListTypeUtils;
import com.sctvcloud.qingchuan.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 更多公众号
 */
public class MoreAccountActivity extends BaseAccountActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, AccountTypeAdapter.OnTypeClickListener
        , AccountAdapter.OnAccountSubscribeClickListener, AccountAdapter.OnAccountClickListener {

    @BindView(R.id.input_key)
    protected EditText searchKey;
    @BindView(R.id.clean_input)
    protected RelativeLayout cleanBtn;
    @BindView(R.id.left_list)
    protected RecyclerView leftListRecyclerView;

    @BindView(R.id.refresh_layout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;

    private AccountTypeAdapter typeAdapter;
    private AccountAdapter adapter;
    private int mPageNo = 1;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private List<AccountTagBean> tagList = new ArrayList<>();
    private List<AccountVo> voList = new ArrayList<>();
    private List<IListShowData> dataList = new ArrayList<>();
    private List<String> authorList = new ArrayList<>();
    private int currentTagIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        new TitleUtils(this).useAndSetTxTitle("关注更多媒体号");
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_more_account);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        leftListRecyclerView.setItemAnimator(new DefaultItemAnimator());
        leftListRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setLoadMoreEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        //设置RecycleView显示的方向是水平还是垂直 GridLayout.HORIZONTAL水平  GridLayout.VERTICAL默认垂直
        gridLayoutManager.setOrientation(GridLayout.VERTICAL);
        //设置布局管理器， 参数gridLayoutManager对象
        mRecyclerView.setLayoutManager(gridLayoutManager);
//        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        getAccountType();
        searchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = searchKey.getText().toString().trim();
                if (TextUtils.isEmpty(str)) {
                    cleanBtn.setVisibility(View.GONE);
                } else {
                    cleanBtn.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void onLoadMore() {
        getData(false);
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        mPageNo = 1;
        getData(true);
    }

    /**
     * 请求公众号
     */
    private void getData(final boolean refresh) {
        String accessToken = "";
        if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
            accessToken = UserManager.getInstance().getUser().getAccountUser().getAccess_token();
        }
        mIsLoading = true;
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("tenantId", Constances.TENANT_ID);
        formMaildata.put("attributeVoList[0].attributeCode", "authorTagId");
        formMaildata.put("attributeVoList[0].attributeValue", authorList.get(currentTagIndex));
        if (!refresh && voList.get(currentTagIndex).getCurrentPage() > 0) {
            formMaildata.put("pageNumber", "" + (voList.get(currentTagIndex).getCurrentPage() + 1));
        } else {
            formMaildata.put("pageNumber", "" + mPageNo);
        }
        formMaildata.put("pageSize", "20");

        Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
        NetUtils.getNetAdapter().getAccountListString(getOwnerName(), accessToken, bodyMap, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        AccountVo bean = gson.fromJson(news, AccountVo.class);
                        if (refresh) {
                            bean.setAuthorTagId(voList.get(currentTagIndex).getAuthorTagId());
                            voList.set(currentTagIndex, bean);
                        } else {
                            if (bean != null && ListUtils.isListValued(bean.getPageRecords())) {
                                voList.get(currentTagIndex).getPageRecords().addAll(bean.getPageRecords());
                                bean.setPageRecords(voList.get(currentTagIndex).getPageRecords());
                                voList.set(currentTagIndex, bean);
                            }
                        }
                        dataList.clear();
                        dataList.addAll(voList.get(currentTagIndex).getPageRecords());
                        initData(dataList);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                    if (ListUtils.isListValued(voList.get(currentTagIndex).getPageRecords())) {
                        dataList.clear();
                        dataList.addAll(voList.get(currentTagIndex).getPageRecords());
                        initData(dataList);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);

            }

            @Override
            public void onEnd() {
                onNetFinish();
                mIsLoading = false;
            }
        });

    }

    private void getAccountType() {
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("tenantId", Constances.TENANT_ID);
        Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
        NetUtils.getNetAdapter().getAccountTag(getOwnerName(), bodyMap, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        tagList = gson.fromJson(news, ListTypeUtils.AccountTagBean());
                        if (ListUtils.isListValued(tagList)) {
                            initTypeData();
                            leftListRecyclerView.setVisibility(View.VISIBLE);
                        } else {
                            leftListRecyclerView.setVisibility(View.GONE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });


    }

    private void initTypeData() {
        if (ListUtils.isListValued(tagList)) {
            AccountVo vo;
            for (int i = 0; i < tagList.size(); i++) {
                authorList.add(tagList.get(i).getAuthorTagId());
                vo = new AccountVo();
                vo.setAuthorTagId(tagList.get(i).getAuthorTagId());
                voList.add(vo);
            }
            tagList.get(0).setSelected(true);
            mRefreshLayout.autoRefresh();
        }
        if (null == adapter) {
            typeAdapter = new AccountTypeAdapter(this, this);
            typeAdapter.setData(tagList);
            leftListRecyclerView.setAdapter(typeAdapter);
            typeAdapter.notifyDataSetChanged();
        }

    }

    private void initData(List<IListShowData> newsItems) {
        if (null == adapter) {
            adapter = new AccountAdapter(this, newsItems, 1,this, this);
            mRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            adapter.setData(newsItems);
        }

    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(voList.get(currentTagIndex).isHasNextPage());

    }

    @Override
    public void OnTypeClick(int position) {

        for (int i = 0; i < tagList.size(); i++) {
            if (i == position) {
                tagList.get(i).setSelected(true);
            } else {
                tagList.get(i).setSelected(false);
            }
        }
        typeAdapter.setData(tagList);
        //TODO 选择类型
        currentTagIndex = position;
        dataList.clear();
        mPageNo = 1;
        if (ListUtils.isListValued(voList.get(currentTagIndex).getPageRecords())) {
            dataList.addAll(voList.get(currentTagIndex).getPageRecords());
            adapter.setData(dataList);
        } else {
            getData(true);
        }

    }

    @Override
    public void OnAccountClick(AccountBean bean) {
        //TODO 点击公众号
        Intent intent = new Intent(this, AccountDetailActivity.class);
        intent.putExtra(AccountDetailActivity.ACCOUNT_ID, bean.getUserId());
        startActivityForResult(intent, 1);
    }

    @Override
    public void OnSubscribeClick(AccountBean bean) {
        //TODO 关注、取消关注公众号
        for (int i = 0; i < dataList.size(); i++) {
            AccountBean da = (AccountBean) dataList.get(i);
            if (bean.getUserId().equalsIgnoreCase(da.getUserId())) {
                toAttentionClick(bean);
                break;
            }
        }
        setResult(RESULT_OK);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            //TODO  搜索
            String key = searchKey.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("请输入关键词");
            } else {
                Intent intent = new Intent(this, AccountSearchActivity.class);
                intent.putExtra(AccountSearchActivity.INPUT_KEY, key);
                startActivityForResult(intent, 1);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                mRefreshLayout.autoRefresh();
                setResult(RESULT_OK);
            }
        }
    }

    @OnClick(value = {R.id.title_top_back, R.id.clean_input})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_back:
                onBackPressed();
                break;
            case R.id.clean_input:
                searchKey.setText("");
                break;
        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param bean
     */
    private void toAttentionClick(final AccountBean bean) {
        if (bean.isAttention()) {
            toUnAttentionAccount(bean.getUserId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    for (int i = 0; i < dataList.size(); i++) {
                        AccountBean da = (AccountBean) dataList.get(i);
                        if (bean.getUserId().equalsIgnoreCase(da.getUserId())) {
                            ((AccountBean) dataList.get(i)).setAttention(false);
                            adapter.setData(dataList);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    if(ListUtils.isListValued(voList)) {
                        for (int i = 0; i < voList.size(); i++) {
                            List<AccountBean> accountList =  voList.get(i).getPageRecords();
                            if(ListUtils.isListValued(accountList)){
                                for (int k = 0; k < accountList.size(); k++) {
                                    AccountBean da = (AccountBean) accountList.get(k);
                                    if (bean.getUserId().equalsIgnoreCase(da.getUserId())) {
                                        ((AccountBean) accountList.get(k)).setAttention(false);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            });
        } else {
            toAttentionAccount(bean.getUserId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    for (int i = 0; i < dataList.size(); i++) {
                        AccountBean da = (AccountBean) dataList.get(i);
                        if (bean.getUserId().equalsIgnoreCase(da.getUserId())) {
                            ((AccountBean) dataList.get(i)).setAttention(true);
                            adapter.setData(dataList);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    if(ListUtils.isListValued(voList)) {
                        for (int i = 0; i < voList.size(); i++) {
                            List<AccountBean> accountList =  voList.get(i).getPageRecords();
                            if(ListUtils.isListValued(accountList)){
                                for (int k = 0; k < accountList.size(); k++) {
                                    AccountBean da = (AccountBean) accountList.get(k);
                                    if (bean.getUserId().equalsIgnoreCase(da.getUserId())) {
                                        ((AccountBean) accountList.get(k)).setAttention(true);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }

}
